package task

import (
	"context"
	"fmt"

	_ "github.com/gogf/gf/contrib/drivers/mysql/v2"

	"github.com/beherochuling/beesoft_api/app/dao"
	"github.com/beherochuling/beesoft_api/app/model/entity"
)

var (
	typeGroups   []string
	typeGroupMap = map[uint]string{}
	types        []string
	typeMap      = map[uint]string{}
)

func init() {
	ctx := context.Background()
	items := TaskType.Scans(ctx)

	for _, item := range items {
		if item.ParentId == 0 {
			typeGroups = append(typeGroups, item.Slug)
			typeGroupMap[item.Id] = item.Slug
		}
	}

	for _, item := range items {
		if item.ParentId != 0 {
			slug := fmt.Sprintf("%s/%s", typeGroupMap[item.ParentId], item.Slug)

			types = append(types, slug)
			typeMap[item.Id] = slug
		}
	}
}

var TaskType = taskType{}

type taskType struct{}

// ## curd

func (r *taskType) Scan(ctx context.Context) *entity.TaskBaseTypes {
	var item *entity.TaskBaseTypes
	err := dao.TaskBaseTypes.Ctx(ctx).
		Scan(&item)
	if err != nil {
		panic(err)
	}

	return item
}
func (r *taskType) Scans(ctx context.Context) []entity.TaskBaseTypes {
	var items []entity.TaskBaseTypes
	err := dao.TaskBaseTypes.Ctx(ctx).
		Scan(&items)
	if err != nil {
		panic(err)
	}

	if len(items) == 0 {
		panic("task type empty")
	}

	return items
}

// ## 封装

func (r *taskType) GetGroups() []string {
	return typeGroups
}
func (r *taskType) GetGroupMap() map[uint]string {
	return typeGroupMap
}
func (r *taskType) GetTypes() []string {
	return types
}
func (r *taskType) GetTypeMap() map[uint]string {
	return typeMap
}
